<?php
/*defined('YII_DEBUG') or define('YII_DEBUG', true);//关闭调试模式设置为false
defined('YII_ENV') or define('YII_ENV', 'dev');//产品发布设置为prod，调试请用dev
require(__DIR__ . '/../../../vendor/autoload.php');
require(__DIR__ . '/../../../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../../../config/web.php');
use app\modules\userabout\models;
// 创建、配置、一个应用，但不执行run方法
$app=(new yii\web\Application($config));
*/
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require(__DIR__ . '/../../../vendor/autoload.php');
require(__DIR__ . '/../../../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../../../config/web.php');
use app\modules\userabout\models;


// 创建、配置、一个应用，但不执行run方法
$app=(new yii\web\Application($config));
require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';

//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
        //$data=json_decode('{"appid":"wxda610a73f463f6d5","attach":"356|=|2","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1398996202","nonce_str":"ne8af7mrr8bdz9p8ojby03u74akaa6rh","openid":"oKnRmwuFS4a09q4LGG0Vw0IqheC8","out_trade_no":"139899620220161028202402","result_code":"SUCCESS","return_code":"SUCCESS","sign":"A92B4077C29795E6C75817E9EC7563A0","time_end":"20161028203543","total_fee":"1","trade_type":"JSAPI","transaction_id":"4005442001201610288002461112","payment_id":"356","type":"2"}',true);
		Log::DEBUG("call back:" . json_encode($data));


		$notfiyOutput = array();
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性

		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}

        $vars=1;
        $pam64=$data["attach"];
        $par=explode("|=|",$pam64);

        $data["payment_id"]=$par[0];
        $data["type"]=$par[1];
        $a=new \app\modules\userabout\models\UserEnpty();
        $SendMobileMsg=new app\modules\admin\models\MoblieNote();
        $datas["_parms"]=json_encode($data);
        //$resultss=$a->Weixinrebacktest($datas);


            $result = $a->Weixinreback($data);

        if($par[1]==1 ||$par[1]=="1")
        {

            $ProcedureMsg=array(
                'Procedure_name'=>'Api_Msg_IfSendMsg',
                'Procedure_data_in'=>array(
                    '_waitfp_id'=>$result[1][0]['@waitfp_id'],
                    '_order_id'=>$result[1][0]['@rental_id'],
                ),
            );
            try {
                $Msgdata = $a->Usermaininfo_query($ProcedureMsg);
            }  catch (\Exception $ex) {
                $result['err_code'] = 40001;
                $result['err_msg'] = $ex->getMessage(); //  服务器错误
                return json_encode($result);
            }
            if (is_array($Msgdata) && !array_key_exists('result', $Msgdata) && !array_key_exists('value', $Msgdata)) {
            }else{
                $result['err_code'] = 40002;
                $result['err_msg'] = $Msgdata['value'];
                return json_encode($result);
            }
            if($Msgdata[0][0]['_result_state']==1){  //预订支付成功
                try{
                    $returndata=$SendMobileMsg->get_rentcarordertask_note($Msgdata[1][0]['user_mobile'],$Msgdata[1][0]['usercar_nickname'],$Msgdata[1][0]['rental_ordernum'],$Msgdata[1][0]['order_startime'],$Msgdata[1][0]['order_endtime']);
                }catch (\Exception $ex) {
                    $result['err_code'] = 40018;
                    $result['err_msg'] = $ex->getMessage(); //  加密失败
                    return json_encode($result);
                };
                if($returndata['successed']) {   //成功返回  "1"
                }else{
                    $result['err_code'] = 40018;
                    $result['err_msg'] = '数据异常,短信发送失败'; //  加密失败
                    return json_encode($result);
                }
            }elseif($Msgdata[0][0]['_result_state']==2) {   //修改租期成功
                try{
                    $returndata=$SendMobileMsg->get_updrent_note($Msgdata[1][0]['user_mobile'],$Msgdata[1][0]['usercar_nickname'],$Msgdata[1][0]['rental_ordernum'],$Msgdata[1][0]['startime'],$Msgdata[1][0]['endtime'],$Msgdata[1][0]['order_startime'],$Msgdata[1][0]['order_endtime']);
                }catch (\Exception $ex) {
                    $result['err_code'] = 40018;
                    $result['err_msg'] = $ex->getMessage(); //  加密失败
                    return json_encode($result);
                };
                if($returndata['successed']) {   //成功返回  "1"
                }else{
                    $result['err_code'] = 40018;
                    $result['err_msg'] = '数据异常,短信发送失败'; //  加密失败
                    return json_encode($result);
                }
            }else{
            }
        }
        else if($par[1]==2 ||$par[1]=="2")
        {

        }


        //todo
        //修改存贮过程


        if($vars==1)
		    return true;
        else
            return false;
	}



}
//ini_set("display_errors", "On");
//error_reporting(E_ALL);
Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
//$a="111";
//$notify->NotifyProcess("1",$a);
//echo 'aaa';
$notify->Handle(false);



//实例化结束





